import { InjectRepository } from '@nestjs/typeorm';
import { PaymentOrder } from './payment-order.entity';
import { DataSource, Repository } from 'typeorm';
import { Inject, Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
// import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { Cache } from 'cache-manager';
import { CACHE_MANAGER } from '@nestjs/cache-manager';
import { PaymentOrderListDto } from './dto/list.dto';
import { PagingResponse } from 'src/constants/common.constants';
import { EditPaymentOrderDto } from './dto/edit.dto';
import { AddPaymentOrderDto, CreatePaymentOrderDto } from './dto/add.dto';

@Injectable()
export class AppPaymentOrderService {
  constructor(
    @InjectRepository(PaymentOrder)
    private readonly paymentOrderRepository: Repository<PaymentOrder>,
    private dataSource: DataSource,
    private configService: ConfigService,
    @Inject(CACHE_MANAGER)
    private cacheManager: Cache,
  ) {}

  async findAll(
    params: PaymentOrderListDto,
  ): Promise<PagingResponse<PaymentOrder>> {
    const [items, total] = await this.paymentOrderRepository.findAndCount({
      where: {
        ...params.params,
      },
    });
    const { pageSize, pageNum } = params;
    return {
      records: items,
      total,
      pageSize,
      current: pageNum,
      pages: Math.ceil(total / pageSize),
    };
  }
  getUserDetail(id: number): Promise<PaymentOrder> {
    return this.paymentOrderRepository.findOne({
      where: { id },
    });
  }
  async update(data: EditPaymentOrderDto) {
    // return this.paymentOrderRepository.save({
    //   ...data,
    // });
    return this.paymentOrderRepository
      .createQueryBuilder()
      .update('payment_order')
      .set({
        ...data,
      })
      .where('id = :id', { id: data.id })
      .execute();
  }

  // async updateByCode(data: EditPaymentOrderDto) {
  //   // return this.paymentOrderRepository.save({
  //   //   ...data,
  //   // });
  //   return this.paymentOrderRepository
  //     .createQueryBuilder()
  //     .update('payment_order')
  //     .set({
  //       ...data,
  //     })
  //     .where('order_code = :order_code', { orderCode: data.orderCode })
  //     .execute();
  // }

  async updateVip(data: { vip: number; id: number }): Promise<PaymentOrder> {
    return this.paymentOrderRepository.save({
      ...data,
    });
  }

  async findOneByTransactionId(transactionId: string) {
    return await this.paymentOrderRepository.findOne({
      where: {
        transactionId,
      },
    });
  }

  async findByUserTransactionId(transactionId: string, userId: string) {
    return await this.paymentOrderRepository.findOne({
      where: {
        transactionId,
        userId,
      },
    });
  }

  async remove(id: number): Promise<void> {
    await this.paymentOrderRepository.delete(id);
  }

  async createMany(users: PaymentOrder[]) {
    const queryRunner = this.dataSource.createQueryRunner();
    await queryRunner.connect();
    await queryRunner.startTransaction();

    try {
      await queryRunner.manager.save(users[0]);
      await queryRunner.manager.save(users[1]);
      await queryRunner.commitTransaction();
    } catch (error) {
      // 如果遇到错误可以回滚事务
      await queryRunner.rollbackTransaction();
    } finally {
      //  手动实例化并部署一个queryRunner
      await queryRunner.release();
    }
  }

  async create(data: CreatePaymentOrderDto) {
    const paymentOrder = this.paymentOrderRepository.create({
      ...data,
      // orderCode: uuidv4(),
      transactionId: '',
      payStatus: 0,
      // appReceipt: '',
    });
    return this.paymentOrderRepository.save(paymentOrder);
  }

  async add(data: AddPaymentOrderDto) {
    const paymentOrder = this.paymentOrderRepository.create({
      ...data,
    });
    return this.paymentOrderRepository.save(paymentOrder);
  }
}
